package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.bottomsheet.PublishBottomSheetFragment;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.socialcontact.adapter.CircleTheHomePageAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.CircleTopicListBean;
import com.yxq.mdt.app.modules.socialcontact.bean.GroupDetailBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.GroupDetailContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.GroupDetailPresenter;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

/**
 * 圈子话题
 */
public class CircleTopicAc extends BaseActivity<GroupDetailPresenter> implements GroupDetailContract.View {

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.topic_text_name)
    TextView topicTextName;
    @BindView(R.id.topic_text_content)
    TextView topicTextContent;
    @BindView(R.id.magic_publish)
    ImageView magicPublish;
    String topicDesc, topicId;
    PublishBottomSheetFragment publishBottomSheetFragment;
    @BindView(R.id.lint_new)
    LinearLayout lintNew;
    @BindView(R.id.lint_hottest)
    LinearLayout lintHottest;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.lint_new_text)
    TextView lintNewText;
    @BindView(R.id.lint_hottest_text)
    TextView lintHottestText;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.lint_hottest_img)
    ImageView lintHottestImg;
    @BindView(R.id.lint_new_img)
    ImageView lintNewImg;
    @BindView(R.id.circle_back)
    LinearLayout circleBack;
    private List<CircleTopicListBean.ListBean> mainSocialContactBeans;
    CircleTheHomePageAdapter circleTopListAdapter;
    String mResidence = "";
    String groupId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_circle_topic;
    }

    @Override
    public void initView() {
        mainSocialContactBeans = new ArrayList<>();
        titlebar.getCenterTextView().setText(getIntent().getStringExtra("topic"));
        topicDesc = getIntent().getStringExtra("topic");
        topicId = getIntent().getStringExtra("topicId");
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        circleTopListAdapter = new CircleTheHomePageAdapter(R.layout.item_layout_dynamic_list, mainSocialContactBeans);
        recyclerView.setAdapter(circleTopListAdapter);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.getGroupDetail(topicId, topicDesc);
        });
        refreshLayout.setEnableLoadMore(false);
        recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (circleTopListAdapter.countDownTimer != null) {
                    circleTopListAdapter.countDownTimer.onFinish();
                }
                Jzvd.releaseAllVideos();
                MediaPlayerHelper.realese();
            }

        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (circleTopListAdapter.countDownTimer != null) {
                    circleTopListAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }
            }
        });
    }

    public void refresh() {
        mPresenter = new GroupDetailPresenter(this, new MainSocialContactModel());
        refreshLayout.autoRefresh();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new GroupDetailPresenter(this, new MainSocialContactModel());
        refreshLayout.autoRefresh();
    }


    @OnClick(R.id.magic_publish)
    public void onViewClicked() {
        publishBottomSheetFragment = new PublishBottomSheetFragment(titlebar.getCenterTextView().getText().toString(), groupId);
        publishBottomSheetFragment.show(getSupportFragmentManager(), "publishBottomSheetFragment");
    }

    @Override
    public void onLoadGroupDetailSuccess(GroupDetailBean groupDetailBean) {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        setCircleTopicDetail(groupDetailBean);
    }

    /**
     * 设置详情
     *
     * @param groupDetailBean
     */
    private void setCircleTopicDetail(GroupDetailBean groupDetailBean) {
        topicTextName.setText(groupDetailBean.getGroupname());
        topicTextContent.setText(groupDetailBean.getDescription());
        groupId = groupDetailBean.getId();
        //设置背景图
        Glide.with(mActivity).asBitmap().load(groupDetailBean.getBackground()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                circleBack.setBackground(drawable);
            }
        });
        MainSocialContactModel.getTopicList(groupDetailBean.getId(), 1, 30, new ApiModel.CommonCallback<CircleTopicListBean>() {
            @Override
            public void onSuccess(CircleTopicListBean circleTopicListBean) {
                circleTopListAdapter.setNewData(circleTopicListBean.getList());
            }

            @Override
            public void onError(String errMsg) {

            }
        });
        //最热的动态
        lintHottest.setOnClickListener(view -> {
            lintHottestText.setTextSize(18);
            lintHottestText.setTextColor(getResources().getColor(R.color.color_font_black));
            lintNewText.setTextColor(getResources().getColor(R.color.gray_pressed));
            lintNewText.setTextSize(16);
            lintHottestImg.setVisibility(View.VISIBLE);
            lintNewImg.setVisibility(View.GONE);
            mPresenter.getTopList(groupDetailBean.getId(), 1, 30, "gt.view_count desc");
        });
        //最新的动态
        lintNew.setOnClickListener(view -> {
            lintNewText.setTextColor(getResources().getColor(R.color.color_font_black));
            lintNewText.setTextSize(18);
            lintHottestImg.setVisibility(View.GONE);
            lintHottestText.setTextSize(16);
            lintHottestText.setTextColor(getResources().getColor(R.color.gray_pressed));
            lintNewImg.setVisibility(View.VISIBLE);
            MainSocialContactModel.getTopicList(groupDetailBean.getId(), 1, 30, new ApiModel.CommonCallback<CircleTopicListBean>() {
                @Override
                public void onSuccess(CircleTopicListBean circleTopicListBean) {
                    circleTopListAdapter.setNewData(circleTopicListBean.getList());
                    mResidence = circleTopicListBean.getList().get(0).getId();
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }

                @Override
                public void onError(String errMsg) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();

                }
            });
        });
        circleTopListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.item_layout_nike_img:
                    if (circleTopListAdapter.countDownTimer != null) {
                        circleTopListAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent it = new Intent(mActivity, SocialPersonalHomepageAc.class);
                    it.putExtra("userId", circleTopListAdapter.getItem(position).getCreateMan());
                    startActivity(it);
                    break;
                case R.id.item_layout_content_browse_img:
                    int giveNum = circleTopListAdapter.getItem(position).getUpCount();
                    if (circleTopListAdapter.getItem(position).getGiveLike() != 0) {
                        MainSocialContactModel.delGsTopicFavour("2", circleTopListAdapter.getItem(position).getId(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                circleTopListAdapter.getItem(position).setGiveLike(0);
                                circleTopListAdapter.getItem(position).setUpCount(giveNum - 1);
                                showCenterToast("取消点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("取消点赞失败");
                            }
                        });
                    } else {
                        MainSocialContactModel.saveGsTopicFavour(circleTopListAdapter.getItem(position).getId(), "2", new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                circleTopListAdapter.getItem(position).setGiveLike(1);
                                circleTopListAdapter.getItem(position).setUpCount(giveNum + 1);
                                showCenterToast("点赞成功");
                                circleTopListAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("点赞失败");
                            }
                        });
                    }
                    break;
                case R.id.item_layout_attention:
                    TextView attention = view.findViewById(R.id.item_layout_attention);
                    MainSocialContactModel.setInterestRelation(circleTopListAdapter.getItem(position).getCreateMan() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            attention.setVisibility(View.GONE);
                            showCenterToast("关注成功");
                        }

                        @Override
                        public void onError(String errMsg) {
                            showCenterToast("关注失败");
                        }
                    });
                    break;
                case R.id.item_tv_subject:
                    refreshLayout.autoRefresh();
                    break;
                case R.id.item_layout_content_share:
                    //分享
                    ShareBean shareBean = new ShareBean();
                    if (!TextUtils.isEmpty(circleTopListAdapter.getItem(position).getContent())) {
                        shareBean.setTitle(circleTopListAdapter.getItem(position).getContent());//文本
                        shareBean.setText(circleTopListAdapter.getItem(position).getContent());//文本
                    } else {
                        shareBean.setTitle("社交电商新玩法，好玩让你意想不到。");//文本
                        shareBean.setText("社交电商新玩法，好玩让你意想不到。");//文本
                    }
                    shareBean.setShareType("0");//图文分享
                    shareBean.setShareTypeAPP(2);
                    shareBean.setHandleId(circleTopListAdapter.getItem(position).getId());
                    if (circleTopListAdapter.getItem(position).getTopicFileList() != null && circleTopListAdapter.getItem(position).getTopicFileList().size() > 0 && "1".equals(circleTopListAdapter.getItem(position).getTopicFileList().get(0).getClass1())) {
                        shareBean.setImageUrl(circleTopListAdapter.getItem(position).getTopicFileList().get(0).getFile());//LOGO
                    } else {
                        shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                    }
                    if (!"release".equals(BuildConfig.RELEASE)) {
                        shareBean.setUrl("http://testpm.quai69.com/webtrends.html?topicId=" + circleTopListAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());//分享URL
                    } else {
                        shareBean.setUrl("http://pm.quai69.com/webtrends.html?topicId=" + circleTopListAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());
                    }
                    ShareSheetDialog shareSheetDialog = new ShareSheetDialog(shareBean, false);
                    shareSheetDialog.show(getSupportFragmentManager(), "shareSheetDialog");
            }
        });
        circleTopListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent it = new Intent(mActivity, SocialStateDetailsAc.class);
            it.putExtra("topicId", circleTopListAdapter.getItem(position).getId());
            it.putExtra("id", circleTopListAdapter.getItem(position).getId());
            startActivity(it);
        });

    }

    @Override
    public void onLoadGroupDetailFailed() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadTopListSuccess(CircleTopicListBean circleTopicListBean) {
        if (circleTopicListBean.getList() != null || circleTopicListBean.getList().size() != 0) {
            circleTopListAdapter.setNewData(circleTopicListBean.getList());
        }
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadTopListFailed() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (circleTopListAdapter.countDownTimer != null) {
            circleTopListAdapter.countDownTimer.onFinish();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Jzvd.backPress()) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }
}
